<template>
  <ProTable
    class-name="no-card customTable"
    ref="proTable"
    :columns="columns"
    :request-api="getWorkRateApi"
    :init-param="initParam"
    :pagination="true"
    :border="false"
    :tool-button="false"
    :cell-class-name="tableColClassName"
    @row-click="rowClick"
    :show-summary="true"
    :summary-method="getSummaries"
    @mouseover="clearScroll"
    @mouseleave="createScroll"
    :key="activeTab"
    :default-expand-all="false"
  >
  </ProTable>
  <!-- <div slot="region" slot-scope="text" class="f-12" style="background: none">{{ title }}</div> -->
</template>

<script setup lang="tsx">
import { reactive, ref, withDefaults, watch, onMounted, onUnmounted, nextTick } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import type { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import { getWorkRateApi } from "@/api/modules/workItem";

interface Props {
  activeTab: string;
}

const props = withDefaults(defineProps<Props>(), { activeTab: "年" });

const proTable = ref<ProTableInstance>();
const emit = defineEmits(["clickEvent"]);
const initParam = reactive({ departmentId: "1" });
let timer: any = null;

onMounted(() => {
  createScroll();
});

// 表格配置项
const columns = ref<ColumnProps<any>[]>([
  { prop: "主责部门", label: "部门", showOverflowTooltip: false },
  { prop: "全年受理总量", label: "受理量", width: "75" },
  { prop: "全年累计解决量", label: "解决量", width: "75" },
  { prop: "全年累计解决率", label: "解决率", width: "90", showOverflowTooltip: false },
  { prop: "超时工单", label: "超时量", width: "70" },
  { prop: "当月不满意工单", label: "低满量", width: "70" }
]);

// 滚动表格
const createScroll = () => {
  // if (isPaused.value) return;
  nextTick(() => {
    clearScroll();
    const tableInstance: any = proTable.value;
    const table = tableInstance.element.$refs;
    const tableWrapper = table.bodyWrapper.firstElementChild.firstElementChild;
    const rows = tableWrapper.children;
    const scrollSpeed = 1; // 滚动速度，值越小滚动越慢
    timer = setInterval(() => {
      tableWrapper.scrollTop += scrollSpeed;
      // console.log(tableWrapper.clientHeight, tableWrapper.scrollTop, rows[0].offsetHeight);
      if (tableWrapper.clientHeight + tableWrapper.scrollTop >= rows[0].offsetHeight) {
        tableWrapper.scrollTop = 0;
        tableWrapper.appendChild(rows[0]);
      }
    }, 30);
  });
};

// 停止滚动
const clearScroll = () => {
  clearInterval(timer);
  timer = null;
};

// 暂停滚动
// const isPaused = ref(false);
// const pauseScroll = () => {
//   isPaused.value = true;
//   clearScroll();
// };

// // 恢复滚动
// const resumeScroll = () => {
//   isPaused.value = false;
//   createScroll();
// };

// 销毁滚动
onUnmounted(() => {
  clearScroll();
});

// 单击行
const rowClick = (row: any, column: TableColumnCtx<any>) => {
  // console.log(row, column);
  emit("clickEvent", "倒三角支撑", []);
  column;
};

// 标注背景颜色
const tableColClassName = ({ column, row }: { column: any; columnIndex: number; row: any; rowIndex: number }) => {
  if (column.label === "部门") return "white-text";
  if (column.label === "受理量" || column.label === "解决率") return "success-row";
  return "default-row";
  row;
};

// 表尾合计行（自行根据条件计算）
interface SummaryMethodProps<T = any> {
  columns: TableColumnCtx<T>[];
  data: T[];
}

// 表尾合计行
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  // console.log(columns, data);
  const sums: any[] = [];

  columns.forEach((column, index) => {
    if (index === 0) return (sums[index] = "合计");
    else {
      // values是每一列的数据是一个数组
      // const values = data.map(item => Number(item[column.property]));
      // const values = data.slice(0, -1).map(item => Number(item[column.property]));

      // // 数字列才进行合计计算
      // if (!values.every(value => isNaN(value))) {
      //   // 对values进行一个累加操作，累加那些非NAN的值
      //   const total = values.reduce((prev, curr) => {
      //     const value = Number(curr);
      //     if (!isNaN(value)) {
      //       return prev + curr;
      //     } else {
      //       return prev;
      //     }
      //   }, 0);

      //   // 年龄计算平均值
      //   if (column.property == "age") {
      //     sums[index] = total / data.length;
      //   }

      //   // 财产计算总数
      //   if (column.property == "money") {
      //     sums[index] = total;
      //   }
      const lastRow = data[data.length - 1];
      if (lastRow) {
        sums[index] = <span class={"info-row"}>{lastRow[column.property]}</span>;
      } else {
        sums[index] = null; // or some default value
      }
      // sums[index] = <span class={"info-row"}>{data[data.length - 1][column.property]}</span>;
    }
  });
  return sums;
};

// 监听activeTab变化
watch(
  () => props.activeTab,
  () => {
    createScroll();
    if (props.activeTab === "年") {
      columns.value = [
        { prop: "主责部门", label: "部门", showOverflowTooltip: false },
        { prop: "全年受理总量", label: "受理量", width: "75" },
        { prop: "全年累计解决量", label: "解决量", width: "75" },
        { prop: "全年累计解决率", label: "解决率", width: "80", showOverflowTooltip: false },
        { prop: "超时工单", label: "超时量", width: "75" },
        { prop: "当月不满意工单", label: "低满量", width: "75" }
      ];
    } else {
      columns.value = [
        { prop: "主责部门", label: "部门", showOverflowTooltip: false },
        { prop: "当月受理量", label: "受理量", width: "75" },
        { prop: "当月解决量", label: "解决量", width: "75" },
        { prop: "当月解决率", label: "解决率", width: "80", showOverflowTooltip: false },
        { prop: "超时工单", label: "超时量", width: "75" },
        { prop: "当月不满意工单", label: "低满量", width: "75" }
      ];
    }
  }
);
</script>

<style lang="scss" scoped></style>
